import beagle
import gobject
import time

class Beagle:

	client = beagle.Client()
	
	def __init__(self):
		request = beagle.DaemonInformationRequest(True,True,True,True)
		response = Beagle.client.send_request (request)
		del request
		request = None
		self.version = response.get_version()
		self.status = response.get_human_readable_status()
		dir(self.status)
		self.index_info = response.get_index_information()
		self.indexing = response.is_indexing()
		response = None
		del response
		

class Pager:

	def __init__(self, pagesize, items):
		self.pagesize = pagesize
		self.items = items
		self.curindex = 0;
		if self.items is None:
			self.endindex = 0
		else:
			self.endindex = len(self.items)
			
	def element_at(self, index):
		return self.items[index]
		
	def has_page(self):
		return self.curindex < self.endindex
		
	def has_next(self): 
		return self.curindex + self.pagesize < self.endindex
	
	def has_prev(self): 
		return self.curindex - self.pagesize >= 0
		
	def page(self):
		if self.curindex + self.pagesize < self.endindex:
			return self.items[self.curindex:self.curindex + self.pagesize]
		else:
			return self.items[self.curindex:self.endindex]
			
	def next(self):
		self.curindex += self.pagesize
		if self.curindex > self.endindex:
			self.reset()
		
	def prev(self):
		self.curindex -= self.pagesize
		if self.curindex < 0:
			self.reset()
	
	def reset(self):
		self.curindex = 0
		
			
class Query:
	
	def __init__(self, text, start=None, end=None):
		self.bquery = beagle.Query()
		self.bquery.add_text(text);
		if start is not None and end is not None:
			self.dpart = beagle.QueryPartDate()
			self.dpart.set_start_date(beagle.beagle_timestamp_new_from_unix_time (start))
			self.dpart.set_end_date(beagle.beagle_timestamp_new_from_unix_time(end))
			self.bquery.add_part(self.dpart)
		
	def get_hits(self):
		if self.response is not None:
			return self.response.get_hits()
		else:
			return None
	
	def _hits_added_cb (self, query, response):
		self.response = response

	def _finished_cb(self, query, response, loop):
		self.main_loop.quit()
		
	def execute(self):
		self.response = None
		self.main_loop = gobject.MainLoop()
		self.bquery.connect("hits-added", self._hits_added_cb)
		self.bquery.connect("finished", self._finished_cb, self.main_loop)
		Beagle.client.send_request_async(self.bquery)
		self.main_loop.run()
			

class SnippetRequest:
	
	def __init__(self, query, hit):
		self.req = beagle.SnippetRequest()
		self.req.set_query(query)
		self.req.set_hit(hit)
		self.hit = hit
		self.snippet = ''
		
	def execute(self):
		self.main_loop = gobject.MainLoop()
		self.req.connect('response', self._on_snippet_received, self.hit)
		self.req.connect('closed', self._on_snippet_closed, self.hit)
		Beagle.client.send_request_async(self.req)
		self.main_loop.run()
		
	def _on_snippet_received(self, request, response, hit):
		self.snippet = response.get_snippet()
    
	def _on_snippet_closed(self, request, hit):
		self.main_loop.quit()



